/**
 * 
 */
package com.feib.stms.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jimmy Liu
 * 
 */
public class FileMD5CheckSumUtil implements Serializable {
	
	private static final long serialVersionUID = 2496843815030142509L;
	
	private static FileMD5CheckSumUtil instance = null;
	
	protected static Logger logger = LoggerFactory.getLogger(FileMD5CheckSumUtil.class);
	
	private FileMD5CheckSumUtil() {	}

	public static FileMD5CheckSumUtil getInstance() {
		if (instance == null) {
			synchronized (StmsUtil.class) {
				if (instance == null) {
					instance = new FileMD5CheckSumUtil();
				}
			}
		}
		return instance;
	}

	public String getMD5Checksum(String filePath) throws Exception {
		byte[] b = null;
		try {
			b = createChecksum(filePath);
		} catch (Exception e) {
			logger.error("File MD5 Hashing error",e);
			throw new Exception("計算檔案MD5發生錯誤！", e);
		}
		String result = "";

		for (int i = 0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
		return result;
	}

	public byte[] createChecksum(String filename) throws NoSuchAlgorithmException, IOException {
		InputStream fis = new FileInputStream(filename);

		byte[] buffer = new byte[1024];
		MessageDigest complete = MessageDigest.getInstance("MD5");
		int numRead;

		do {
			numRead = fis.read(buffer);
			if (numRead > 0) {
				complete.update(buffer, 0, numRead);
			}
		} while (numRead != -1);

		fis.close();
		return complete.digest();
	}

}
